import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import type { LoginForm, UserInfo } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken() || '')
  const userInfo = ref<UserInfo>({
    id: '',
    username: '',
    nickname: '',
    avatar: '',
    email: '',
    phone: '',
    roles: [],
    permissions: [],
    deptId: '',
    deptName: '',
    companyId: '',
    companyName: ''
  })
  const roles = ref<string[]>([])
  const permissions = ref<string[]>([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasRole = computed(() => (role: string) => roles.value.includes(role))
  const hasPermission = computed(() => (permission: string) => permissions.value.includes(permission))

  // 登录
  const loginAction = async (loginForm: LoginForm) => {
    try {
      const response = await login(loginForm)
      const { token: newToken } = response.data
      
      token.value = newToken
      setToken(newToken)
      
      ElMessage.success('登录成功')
      return response
    } catch (error) {
      ElMessage.error('登录失败')
      throw error
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      const userData = response.data
      
      userInfo.value = {
        id: userData.id,
        username: userData.username,
        nickname: userData.nickname,
        avatar: userData.avatar || '',
        email: userData.email || '',
        phone: userData.phone || '',
        roles: userData.roles || [],
        permissions: userData.permissions || [],
        deptId: userData.deptId || '',
        deptName: userData.deptName || '',
        companyId: userData.companyId || '',
        companyName: userData.companyName || ''
      }
      
      roles.value = userData.roles || []
      permissions.value = userData.permissions || []
      
      return response
    } catch (error) {
      ElMessage.error('获取用户信息失败')
      throw error
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出接口调用失败:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      userInfo.value = {
        id: '',
        username: '',
        nickname: '',
        avatar: '',
        email: '',
        phone: '',
        roles: [],
        permissions: [],
        deptId: '',
        deptName: '',
        companyId: '',
        companyName: ''
      }
      roles.value = []
      permissions.value = []
      removeToken()
      
      ElMessage.success('退出成功')
    }
  }

  // 重置用户信息
  const resetUserInfo = () => {
    userInfo.value = {
      id: '',
      username: '',
      nickname: '',
      avatar: '',
      email: '',
      phone: '',
      roles: [],
      permissions: [],
      deptId: '',
      deptName: '',
      companyId: '',
      companyName: ''
    }
    roles.value = []
    permissions.value = []
  }

  return {
    // 状态
    token,
    userInfo,
    roles,
    permissions,
    
    // 计算属性
    isLoggedIn,
    hasRole,
    hasPermission,
    
    // 方法
    login: loginAction,
    getUserInfo: getUserInfoAction,
    logout: logoutAction,
    resetUserInfo
  }
})
